package top.drinyeit.weilong.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import top.drinyeit.weilong.R;
import top.drinyeit.weilong.adapter.MyOrderAdapter;
import top.drinyeit.weilong.base.BaseActivity;
import top.drinyeit.weilong.entity.Tag;
import top.drinyeit.weilong.fragment.GoodsSearchFragment;
import top.drinyeit.weilong.fragment.ShopSearchFragment;
import top.drinyeit.weilong.presenter.SearchPresenter;
import top.drinyeit.weilong.view.SearchHistory;
import top.drinyeit.weilong.view.SearchHistoryDao;
import top.drinyeit.weilong.view.SingleTagView;
import top.drinyeit.weilong.view.TagView;


/**
 * Created by bigHead on 2017/11/16.
 */

public class SearchActivity extends BaseActivity {

    int position = 0;
    private String startString;
    private ViewPager search_ViewPager;
    List<Fragment> list = new ArrayList<>();
    private List<String> mNameList;
    MyOrderAdapter myOrderAdapter;
    private LinearLayout merchandise;//商品
    private LinearLayout shop;//店铺
    private TabLayout mTabLayout;
    RelativeLayout search_toolbar;
    EditText search_text;//默认搜索文字
    private SearchPresenter searchPresenter;
    private TextView tv_back;

    MyAdapter myAdapter;
    public ListView history;
    List<List<Tag>> historyList;
    SearchHistoryDao searchHistoryDao;

    Map<String, Object> map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_search);
        search_ViewPager = (ViewPager) findViewById(R.id.search_ViewPager);
        search_toolbar = findViewById(R.id.rl_search_toolbar);
        search_text = findViewById(R.id.et_search_text);
        mTabLayout = findViewById(R.id.mTabLayout);
        tv_back = findViewById(R.id.tv_back);

        history = findViewById(R.id.history);
        searchHistoryDao = new SearchHistoryDao(-1);
        historyList = new ArrayList<>();
        myAdapter = new MyAdapter();
        history.setAdapter(myAdapter);

        initIntent();
        inithistoryList();
        initData();
        init();
        initViewPager();
        setTitle();
    }

    private void initIntent(){
        if (getIntent().getExtras() != null){
            search_text.setText(getIntent().getExtras().getString("search_key"));
        }
    }

    private void initData() {
        searchPresenter = new SearchPresenter(this);
    }

    @Override
    public void init() {
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        search_ViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setPosition(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        search_text.setHint("请输入搜索内容");
        search_text.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String str = search_text.getText().toString().trim();
                SearchHistory searchHistory = new SearchHistory();
                if (str.length() > 0) {
                    searchHistory.setContent(str);
                    setSearchHistory(searchHistory);
                    inithistoryList();
                }
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 当按了搜索之后关闭软键盘
                    ((InputMethodManager) search_text.getContext().getSystemService(
                            Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                            SearchActivity.this.getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    if (search_text.getText().toString().length() == 0) {
                        showToast("请输入搜索内容");
                        return true;
                    }
                    Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
                    intent.putExtra("search_key", search_text.getText().toString());
                    if (position == 0) {
                        intent.putExtra("type", position);
                    } else {
                        intent.putExtra("type", position);
                    }
                    startActivity(intent);
                    return true;
                }
                return false;
            }
        });
    }

    private void setPosition(int position) {
        this.position = position;
        System.out.println("position" + position);
    }

    public void initViewPager() {
        mNameList = new ArrayList<>();
        mNameList.add("商品");
        mNameList.add("店铺");
        list.add(new GoodsSearchFragment());
        list.add(new ShopSearchFragment());
        myOrderAdapter = new MyOrderAdapter(getSupportFragmentManager(), list, mNameList);
        search_ViewPager.setAdapter(myOrderAdapter);
        mTabLayout.setupWithViewPager(search_ViewPager);
    }

    public void inithistoryList() {
        List<SearchHistory> list = searchHistoryDao.findAll();
        historyList = new ArrayList<>();
        if (list == null) {
            list = new ArrayList<>();
        }
        List<Tag> mTags = new ArrayList<>();

        for (SearchHistory se : list) {
            Tag tag = new Tag();
            tag.setId(se.getId());
            tag.setTagType("n");//表示搜索记录
            tag.setChecked(false);
            tag.setTitle(se.getContent());
            mTags.add(tag);

            historyList.add(mTags);
        }
        myAdapter.notifyDataSetChanged();
    }

    public void setSearchHistory(SearchHistory searchHistory) {

        boolean bl = true;

        List<SearchHistory> list = searchHistoryDao.findAll();
        if (list != null) {
            for (SearchHistory se : list) {

                if (se.getContent().equals(searchHistory.getContent())) {
                    bl = false;//如果有记录,不重复增加
                }
            }
            if (bl) {
                searchHistoryDao.save(searchHistory);
            } else {
                searchHistory = null;
            }
        } else {
            searchHistoryDao.save(searchHistory);
        }


        //   this.appUser = getAppUser();
    }

    private class ViewHolder {
        SingleTagView mTagListView;
        TextView text;
        ImageView img;
        LinearLayout delete_ll;
    }


    class MyAdapter extends BaseAdapter implements SingleTagView.OnTagClickListener, SingleTagView.OnTagLongClickListener {
        @Override
        public int getItemViewType(int position) {
            return position % 2;
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getCount() {
            return historyList.size() != 0 ? historyList.size() + 1 : 0;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int position, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            int type = getItemViewType(position);
            if (view == null) {
                viewHolder = new ViewHolder();
                if (position == 0) {
                    view = View.inflate(SearchActivity.this, R.layout.item_search_list_view1, null);
                    viewHolder.text = (TextView) view.findViewById(R.id.textStr);
                    viewHolder.img = (ImageView) view.findViewById(R.id.img);
                    viewHolder.delete_ll = (LinearLayout) view.findViewById(R.id.delete_ll);
                } else {
                    view = View.inflate(SearchActivity.this, R.layout.item_search_list_view, null);
                    viewHolder.mTagListView = (SingleTagView) view.findViewById(R.id.tagview);
                }
                view.setTag(viewHolder);
            }
            viewHolder = (ViewHolder) view.getTag();
            if (position == 1) {
                viewHolder.mTagListView.setIsSingle(true);
                viewHolder.mTagListView.setTags(historyList.get(0));
                viewHolder.mTagListView.setOnTagClickListener(this);
                viewHolder.mTagListView.setOnTagLongClickListener(this);

            } else if (position == 0) {
                viewHolder.text.setText("历史搜索");
                viewHolder.img.setVisibility(View.VISIBLE);
                viewHolder.delete_ll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        searchHistoryDao.deleteAll();
                        historyList.get(0).clear();
                        myAdapter.notifyDataSetChanged();
                    }
                });

            }


            return view;
        }

        @Override
        public void onTagClick(TagView tagView, Tag tag, boolean isSinggle) {
            search_text.setText(tagView.getText());
            search_text.setFocusable(true);
            search_text.setFocusableInTouchMode(true);
            search_text.requestFocus();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(search_text, 0);
        }


        @Override
        public void onTagLongClick(TagView tagView, Tag tag, boolean isSinggle) {
            // showToast("23424");
        }

    }

    //删除订单
//    public void deleteOrder(String parent_order_id) {
//        CommonSubscriber<HttpResponse<String>> subscriber = new CommonSubscriber<>(new SubscriberListener<HttpResponse<String>>() {
//            @Override
//            public void onError(String e, int code) {
//                activity.showToastMsg(e);
//            }
//
//            @Override
//            public void onNext(HttpResponse<String> o) {
//                if (o.getCode() == COMMON_SUCCESS) {
//
//                }else {
//                    activity.showToastMsg(o.getMessage());
//                }
//            }
//        });
//        RetrofitMethod.getInstance().deleteOrder(subscriber, parent_order_id);
//    }

    //取消订单
//    public void cancelOrder(String parent_order_id) {
//        CommonSubscriber<HttpResponse<String>> subscriber = new CommonSubscriber<>(new SubscriberListener<HttpResponse<String>>() {
//            @Override
//            public void onError(String e, int code) {
//                activity.showToastMsg(e);
//            }
//
//            @Override
//            public void onNext(HttpResponse<String> o) {
//                if (o.getCode() == COMMON_SUCCESS) {
//
//                }else {
//                    activity.showToastMsg(o.getMessage());
//                }
//            }
//        });
//        RetrofitMethod.getInstance().cancelOrder(subscriber, parent_order_id);
//    }

}
